import { useDeepCompareEffect } from 'ahooks';
import { Modal, Radio, Space } from 'antd';
import type { FC } from 'react';
import { useState } from 'react';
import Search from './Search';

type TProps = {
  visible: boolean;
  onSubmit: TAnyFunction;
  onCancel: TAnyFunction;
  data: any;
  stepThreeRef?: any;
};

const PeriodPickerModal: FC<TProps> = (props) => {
  const { visible, onSubmit, onCancel, data, stepThreeRef } = props;
  const [curType, setCurType] = useState<string>('market');
  const [marketData, setMarketData] = useState<TIdNameData[]>([]);
  const [cityData, setCityData] = useState<TIdNameData[]>([]);
  const [districtData, setDistrictData] = useState<TIdNameData[]>([]);
  const [storeData, setStoreData] = useState<TIdNameData[]>([]);

  const handleTypeChange = (e: any) => {
    setCurType(e.target.value);
  };

  const handleSubmit = () => {
    onSubmit &&
      onSubmit({
        ...(marketData && marketData.length && { market: marketData }),
        ...(cityData && cityData.length && { city: cityData }),
        ...(districtData && districtData.length && { district: districtData }),
        ...(storeData && storeData.length && { store: storeData }),
      });
  };

  useDeepCompareEffect(() => {
    if (data) {
      const { market, city, district, store } = data;
      setMarketData(market || []);
      setCityData(city || []);
      setDistrictData(district || []);
      setStoreData(store || []);
    }
  }, [data]);

  return (
    <Modal title="选择区域范围" open={visible} width={600} onCancel={onCancel} onOk={handleSubmit}>
      <div className="mb-16">
        <Radio.Group value={curType} onChange={handleTypeChange}>
          <Space size={16}>
            <Radio value="market">市场</Radio>
            <Radio value="city">城市</Radio>
            <Radio value="district">城区</Radio>
            <Radio value="store">门店</Radio>
          </Space>
        </Radio.Group>
      </div>

      {{
        market: (
          <Search
            title="市场"
            key="market"
            type="market"
            data={marketData}
            onChange={(val: TIdNameData[]) => setMarketData(val)}
          />
        ),
        city: (
          <Search
            title="城市"
            key="city"
            type="city"
            data={cityData}
            onChange={(val: TIdNameData[]) => setCityData(val)}
          />
        ),
        district: (
          <Search
            title="城区"
            key="district"
            type="district"
            data={districtData}
            onChange={(val: TIdNameData[]) => setDistrictData(val)}
          />
        ),
        store: (
          <Search
            title="门店"
            key="store"
            type="store"
            data={storeData}
            onChange={(val: TIdNameData[]) => setStoreData(val)}
            stepThreeRef={stepThreeRef}
          />
        ),
      }[curType] || null}
    </Modal>
  );
};

export default PeriodPickerModal;
